<template>
  <div class="custom-table">
    <div class="table-header-1" style="justify-content: space-between">
      <div style="display: flex; align-items: center">
        <div class="header-cell" style="color: #000000; font-weight: 600">
          {{ displayNow.rxName || '处方名称' }}
        </div>
        <div style="margin-left: 10px">
          <el-select
            v-model="displayNow.storageId"
            filterable
            style="width: 140px"
            class="borderless-select"
            @change="onStorage(displayNow.detailList)"
            :disabled="visitStatus === '2' || displayNow.payStatus == '2'"
          >
            <el-option
              v-for="frequency in storageList"
              :key="frequency.storageName"
              :label="frequency.storageName"
              :value="frequency.storageId"
            />
          </el-select>
        </div>
      </div>
      <div class="header-cell" v-if="props.visitStatus !== '2'">
        <span style="color: #e37318; margin-right: 10px"
          >费用：￥{{ (displayNow.totalAmount / 100).toFixed(2) }}</span
        >
        <div
          class="header-cell"
          @click="removeRow_1(displayNow.detailList)"
          v-if="displayNow.payStatus != '2'"
        >
          <img src="@/assets/manage/icon_del_nor.svg" alt="" />
        </div>
      </div>
    </div>
    <!-- 表头 -->

    <div class="table-header">
      <div
        v-for="column in props.columns"
        :key="column.key"
        class="header-cell"
        :style="{
          width: column.flex ? undefined : column.width,
          flex: column.flex ? 1 : undefined,
          textAlign: column.align || 'left',
        }"
      >
        <div v-if="column.label === '用量/次'" style="position: relative">
          <!-- 图表悬浮层 -->
          <div
            v-if="chartVisibleColumn && isUserCode"
            class="chart-overlay"
            @click.stop
          >
            <EchartsBar
              :chartVisible="chartVisible"
              :weight="props.weight"
              @changeVisible="changeVisible"
            />
          </div>
          <div>
            {{ column.label }}
          </div>
        </div>
        <div v-else>
          {{ column.label }}
        </div>
      </div>
    </div>

    <!-- 表格数据行 -->
    <div
      v-for="(row, index) in displayNow.detailList"
      :key="row.examId"
      class="table-row-container"
      :class="{ 'add-row': row.isNew }"
    >
      <div class="table-row" :class="{ 'add-row': row.isNew }">
        <div
          v-for="column in props.columns"
          :key="column.key"
          class="table-cell"
          :style="getColumnStyle(column)"
        >
          <!-- 序号列 -->
          <template v-if="column.key === 'index'">
            {{ row.isNew ? '' : index + 1 }}
          </template>

          <!-- 项目列 -->
          <template v-else-if="column.key === 'drugName'">
            <!-- <span>{{ row.drugName }}</span> -->
            <div style="position: relative">
              <span style="display: flex">
                <span
                  @mouseenter="showMedicineInfo(row)"
                  @mouseleave="hideMedicineInfo"
                  class="multi-line"
                >
                  {{ row.drugName }}{{ row.specification }}</span
                >
                <span style="position: relative">
                  <div
                    style="position: absolute; bottom: 20px; right: -530%"
                    v-show="AlertTipsRow == row.uuid"
                  >
                    <AlertTips :tips="row.tips" />
                  </div>
                  <img
                    src="@/assets/icon/icon_jinggao_nor.svg"
                    alt=""
                    v-if="row.tips.length > 0"
                    @mouseenter="showMedicineInfoRow(row)"
                    @mouseleave="hideMedicineInfoRow"
                    style="
                      vertical-align: middle;
                      margin-left: 5px;
                      cursor: pointer;
                    "
                  />
                </span>
              </span>
              <div class="move-Medicine" v-show="hoveredRow == row.uuid">
                <div class="move-Medicine-icon">
                  <div style="width: 100%">
                    <span style="font-size: 16px; color: rgba(0, 0, 0, 0.9)">{{
                      row.drugName
                    }}</span>
                    <div
                      style="
                        display: flex;
                        justify-content: space-between;
                        width: 100%;
                      "
                    >
                      <div>{{ drugProfileDetail.specification }}</div>
                      <span
                        >库存：<span style="font-size: 14px; color: #16ada4"
                          >{{ drugProfileDetail.stockQty
                          }}{{ drugProfileDetail.packUnitText
                          }}{{ drugProfileDetail.minStockQty
                          }}{{ drugProfileDetail.minPackUnitText }}</span
                        ></span
                      >
                    </div>
                  </div>
                </div>
                <div style="margin-top: 20px; margin-left: 5px">
                  <el-tag type="success">{{
                    drugProfileDetail.drugCategoryName
                  }}</el-tag>
                  <el-tag type="warning" style="margin-left: 5px">{{
                    useBaseDataStore.getDRUGINGREnumData(
                      drugProfileDetail.drugIngr,
                      'DRUG_INGR'
                    )
                  }}</el-tag>
                  <el-tag type="primary" style="margin-left: 5px">{{
                    useBaseDataStore.getEnumData(
                      drugProfileDetail.dosageForm,
                      'dosageFormEnum'
                    )
                  }}</el-tag>
                </div>
                <div style="margin-top: 20px; margin-left: 5px">
                  <div style="margin-bottom: 10px">
                    厂家：<span style="color: #000000">{{
                      drugProfileDetail.mfrName
                    }}</span>
                  </div>
                  <div style="margin-bottom: 10px">
                    售价：<span style="color: #000000"
                      >{{ (drugProfileDetail.price / 100).toFixed(2) }}元/盒  
                      {{
                        (drugProfileDetail.splitPrice / 100).toFixed(2)
                      }}元/袋</span
                    >
                  </div>
                  <div style="margin-bottom: 10px">
                    禁用：<span
                      style="color: #000000; white-space: break-spaces"
                      >{{ drugProfileDetail.conflicts }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- 用法列 -->
          <template v-else-if="column.key === 'usageCodeText'">
            <div
              @click.stop="onUsageCode(row)"
              v-if="props.visitStatus !== '2' && displayNow.payStatus != '2'"
              style="
                border: 1px solid #e4e7ed;
                padding: 4px;
                border-radius: 4px;
                height: 32px;
                display: inline-block;
                min-width: 40px;
              "
            >
              {{ row.usageCodeText }}
            </div>
            <div v-else>
              {{ row.usageCodeText }}
            </div>
            <div
              v-if="showMedicationTabs && isShowMedicationTabs === row.uuid"
              @click.stop
              style="position: absolute; top: 30px; left: 0; z-index: 10"
            >
              <MedicationTabs
                @select="(usage: any, usageName: any) => onSelect(row, usage, usageName)"
                :rxType="1"
              />
            </div>
          </template>

          <!-- 频率列 -->
          <template v-else-if="column.key === 'frequencyCode'">
            <el-select
              v-model="row.frequencyCode"
              filterable
              style="width: 100px"
              class="borderless-select"
              suffix-icon=""
              @focus="onfrequency"
              @change="onFrequency(row, index)"
              v-if="props.visitStatus !== '2' && displayNow.payStatus != '2'"
            >
              <!-- <el-option
                v-for="frequency in frequencyOptions"
                :key="frequency.frequencyCode"
                :label="frequency.frequencyName"
                :value="frequency.frequencyCode"
              /> -->
              <el-option
                v-for="frequency in frequencyOptions"
                :key="frequency.frequencyCode"
                :label="frequency.frequencyName"
                :value="frequency.frequencyCode"
                style="padding: 0 8px"
              >
                <span style="float: left">{{ frequency.frequencyCode }}</span>
                <span style="float: right; font-size: 13px">
                  {{ frequency.frequencyName }}
                </span>
              </el-option>
            </el-select>
            <div v-else style="width: 100px">
              {{ row.frequencyCodeText }}
            </div>
          </template>

          <!-- 用量列 -->
          <template v-else-if="column.key === 'dosage'">
            <div
              class="pill-input-unit"
              style="
                display: inline-flex;
                align-items: center;
                gap: 0;
                position: relative;
              "
              v-if="props.visitStatus !== '2' && displayNow.payStatus != '2'"
            >
              <el-input-number
                v-model="row.dosage"
                :max="999"
                :step="0.1"
                :min="0"
                :controls="false"
                class="borderless-input pill-number"
                style="width: 50px"
                @change="updateRow(row, index)"
                @focus="showKeyboard(row, index, 'dosage')"
                @click.stop
              />
              <span class="unit-chip">{{ row.minPackUnitText }}</span>

              <!-- 数字键盘 -->
              <div
                v-if="
                  keyboardVisible &&
                  currentEditRow?.uuid === row.uuid &&
                  currentEditField === 'dosage'
                "
                class="number-keyboard"
                @click.stop
              >
                <NumberDecimal @input="inputNumber" @delete="deleteNumber" />
              </div>
            </div>
            <div v-else>{{ row.dosage }} {{ row.dosageUnitText }}</div>
          </template>
          <!-- 周期 -->
          <template v-else-if="column.key === 'cycle'">
            <div
              v-if="props.visitStatus !== '2' && displayNow.payStatus != '2'"
              style="
                display: flex;
                align-items: center;
                gap: 8px;
                position: relative;
              "
            >
              <el-input-number
                v-model="row.cycle"
                :min="0"
                :max="999"
                :controls="false"
                class="borderless-input"
                style="width: 50px"
                @change="updateRow(row, index)"
                @focus="showKeyboard(row, index, 'cycle')"
                @click.stop
              />
              <span>{{ row.cycleUnitText }}</span>

              <!-- 数字键盘 -->
              <div
                v-if="
                  keyboardVisible &&
                  currentEditRow === row &&
                  currentEditField === 'cycle'
                "
                class="number-keyboard"
                @click.stop
              >
                <NumericKeyboardInt
                  @input="inputNumber"
                  @delete="deleteNumber"
                />
              </div>
            </div>
            <div v-else>{{ row.cycle }} {{ row.cycleUnitText }}</div>
          </template>
          <!-- 总量列 -->
          <template v-else-if="column.key === 'totalOutQty'">
            <div
              v-if="props.visitStatus !== '2' && displayNow.payStatus != '2'"
              style="
                display: flex;
                align-items: center;
                gap: 4px;
                position: relative;
              "
            >
              <el-input-number
                v-model="row.totalOutQty"
                :min="0"
                :max="999"
                :controls="false"
                class="borderless-input"
                ref="searchInputRef"
                style="width: 50px"
                @change="updateRow(row, index)"
                @focus="showKeyboard(row, index, 'totalOutQty')"
                @click.stop
              />
              <span v-if="row.isSplit == '1'">{{ row.minPackUnitText }}</span>
              <span v-else>{{ row.totalOutQtyUnitText }}</span>
              <!-- 总量数字键盘 -->

              <div
                v-if="
                  keyboardVisible &&
                  currentEditRow.uuid === row.uuid &&
                  currentEditField === 'totalOutQty'
                "
                class="number-keyboard"
              >
                <NumericKeyboardInt
                  @input="inputNumber"
                  @delete="deleteNumber"
                />
              </div>
            </div>
            <div v-else>
              {{ row.totalOutQty }} {{ row.totalOutQtyUnitText }}
            </div>
          </template>

          <!-- 备注列 -->
          <template v-else-if="column.key === 'remark'">
            <AutocompleteMulti
              v-model="row.remark"
              class="borderless-select right-select"
              placeholder=""
              style="width: calc(100% - 30px)"
              :trigger-on-focus="true"
              :fetch-suggestions="querySearchAsync"
              :selected-color="'#16ada4'"
              v-if="props.visitStatus !== '2' && displayNow.payStatus != '2'"
            />
            <span v-else>{{ row.remark }}</span>
            <!-- <el-button
              v-if="row.isNew"
              type="primary"
              text
              size="small"
              style="margin-left: 8px"
              @click="confirmAdd(row, index)"
            >
              +
            </el-button> -->
          </template>

          <!-- 自定义列 -->
          <template v-else>
            {{ row[column.key as keyof any] }}
          </template>
        </div>
      </div>

      <!-- 悬浮删除按钮 -->
      <div
        class="delete-button"
        @click="deleteRow(row, index)"
        v-if="props.visitStatus !== '2' && displayNow.payStatus != '2'"
      >
        <img src="@/assets/manage/icon_off_hover.svg" alt="删除" />
      </div>
    </div>
    <!-- 搜索行 -->
    <div
      class="table-row search-row"
      v-if="props.visitStatus !== '2' && displayNow.payStatus != '2'"
    >
      <div
        v-for="(column, columnIndex) in props.columns"
        :key="`search-${column.key}`"
        class="table-cell"
        :style="{
          border: columnIndex === 0 ? 'none' : undefined,
          position: columnIndex === 0 ? 'relative' : undefined,
        }"
      >
        <template v-if="columnIndex === 0">
          <div
            class="table-row"
            style="font-size: 16px; color: #999999; line-height: 50px"
          >
            +
          </div>
          <el-input
            v-model="searchText"
            placeholder="搜索项目名称或拼音缩写"
            class="search-input1"
            style="width: 100%"
            clearable
            @input="handleSearch"
            @focus="showSearchKeyboard"
            @click.stop
          />

          <!-- 搜索全键盘 -->
          <SearchKeyboard
            :mode="keyboardMode"
            @input="(result: any) => inputSearchChar(result)"
            @delete="deleteSearchChar"
            @clear="clearSearch"
            @switch="switchKeyboard"
            @click.stop
            v-if="
              searchKeyboardVisible && displayNow.uuid == props.displayNowUUid
            "
          />
          <!-- 搜索结果下拉列表 -->
          <div
            v-if="
              searchResults.length > 0 &&
              searchKeyboardVisible &&
              displayNow.uuid == props.displayNowUUid
            "
            class="search-results1"
            @click.stop
          >
            <div class="table-header">
              <div
                class="header-cell"
                style="width: 600px; text-align: left; padding-left: 16px"
              >
                药品
              </div>
              <div
                class="header-cell"
                style="width: 120px; text-align: left; padding-left: 16px"
              >
                规格
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                厂家
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                单价
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                单位
              </div>
            </div>
            <div
              v-for="result in searchResults"
              :key="result.projectId"
              class="search-result-item"
              @click="selectSearchResult(result)"
            >
              <div
                class="result-name"
                style="width: 600px; text-align: left; padding-left: 16px"
              >
                {{ result.drugName }}
              </div>
              <div
                class="result-category"
                style="width: 120px; text-align: left; padding-left: 16px"
              >
                {{ result.specification }}
              </div>
              <div
                class="result-spec"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                {{ result.mfrName }}
              </div>
              <div
                class="result-price"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                ¥ {{ (result.price / 100).toFixed(2) }}
              </div>
              <div
                class="result-price"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                {{ result.packUnitText }}
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <!-- 选择模板 -->
    <el-dialog
      v-model="isTemplate"
      class="custom-transition-dialog-1"
      :title="''"
      :width="1200"
      top="5vh"
      @close="isTemplate = false"
    >
      <template #header="{ close, titleId, titleClass }" style="display: none">
        <div class="my-header" style="display: none">
          <el-icon class="el-icon--left">
            <CircleCloseFilled />
          </el-icon>
        </div>
      </template>
      <!-- 1是病历模板 2是检验模板 3是处方模板 -->
      <managePages
        :medicalList="displayNow.detailList"
        @updataTemplate="updataTemplate"
        :activeName_s="'3'"
      />
    </el-dialog>
    <!-- 保存模板 -->
    <addTemplate
      ref="addTemplateRef"
      @addTemplate="onAddTemplate"
    ></addTemplate>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import addTemplate from './addTemplate.vue';
import { CircleCloseFilled } from '@element-plus/icons-vue';
import { getDrugRxList } from '@/api/formwork';
import prescriptionTemplate from './prescriptionTemplate.vue';
import managePages from './managePages.vue';
import { v4 as uuidv4 } from 'uuid';
import { CaretBottom, Star, Delete, Close } from '@element-plus/icons-vue';
import stores from '@/store';
import { getDrugProfileDetail } from '@/api/drug';
import {
  calculateTotalDose,
  calculatePrice,
  validateStorage,
} from '@/utils/rxUtil';
import AlertTips from '@/components/AlertTips.vue';

const useBaseDataStore = stores.useBaseDataStore();
const searchKeyboardOnTop = ref(false);
const searchInputRef = ref<HTMLInputElement | null>(null);
const isTemplate = ref(false);
const currentUsageRow = ref<any | null>(null);
const storageList = ref<any[]>(useBaseDataStore.Storage);
const isShowMedicationTabs = ref<any>(null);
const drugProfileDetail = ref<any>({}); // 用于控制用法选择组件的显示
const AlertTipsRow = ref<any | null>(null);
const tipsList = ref<any[]>([]);
const isUserCode = ref(true);
// 定义数据类型
// interface any {
//   examId: number;
//   projectId: number; // 主键ID
//   projectName: string; // 项目名称;CT
//   price: number; // 价格
//   projectCategory: string; // 项目分类;1检查2.检验3.治疗 projectCategoryEnum
//   projectCategoryName: string; // 项目分类名称
//   projectType: string; // 项目类型;头部CT 如果projectCategory=1取字典中的EXAM_TYPE,projectCategory=2取LAB_TYPE，如果等于3取EXT_TYPE
//   sampleType: string; // 样本类型;如果是检验项目需要维护1.全血 sampleTypeEnum
//   chargeType: string; // 收费类型1项目2穴位 ProjectChargeTypeEnum
//   unit: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
//   unitName: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
//   isNew?: boolean;
//   remark?: string;
//   frequencyCode?: string; // 频率代码
//   frequencyName?: string; // 频率名称
// }
// 添加用于控制图表显示的响应式变量
const chartVisibleColumn = ref<string | null>(null);
const chartVisible = ref<any>({});

// 新增方法：生成提示信息
const generateTips = (row: any) => {
  const data1 = validateStorage(
    row.minPackQty,
    row.stockQty,
    row.minStockQty,
    row.totalOutQty,
    row.isSplit
  );
  //console.log(data1);
  let tips: string[] = [];
  if (!data1 && row.totalOutQty) {
    tips.push('库存不足');
  } else {
    tips = tips.filter((tip) => tip !== '库存不足');
  }
  // if (!row?.usageList) {
  //   return [];
  // }
  if (row?.usageList) {
    const usageList = row?.usageList.find(
      (item: any) => item.usageCode === row?.usageCode
    );
    //console.log(row);
    if (usageList) {
      // const singleMin = (props?.weight * usageList.singleMin) / 50
      const singleMin = Math.round(
        ((props.weight ?? 50) * usageList.singleMin) / 50
      );
      const singleMax = Math.round(
        ((props.weight ?? 50) * usageList.singleMax) / 50
      );
      const dailyMax = Math.round(
        ((props.weight ?? 50) * usageList.dailyMax) / 50
      );
      const average = Math.round((singleMin + singleMax) / 2);

      if (row.dosage && row.dosage < singleMin) {
        tips.push('单次用量低于推荐单次最小用量');
      } else {
        tips = tips.filter((tip) => tip !== '单次用量低于推荐单次最小用量');
      }
      if (row.dosage && row.dosage > singleMax) {
        tips.push('单次用量超过推荐单次最大用量');
      } else {
        tips = tips.filter((tip) => tip !== '单次用量超过推荐单次最大用量');
      }
      if (row.frequencyCode && row.dosage) {
        const totalOutQty =
          getTimesPerDayFromCode(row.frequencyCode) * row.dosage;
        if (totalOutQty && totalOutQty > dailyMax) {
          tips.push('单日用量超过推荐单日最大用量');
        } else {
          tips = tips.filter((tip) => tip !== '单日用量超过推荐单日最大用量');
        }
      }
    }
  }
  return tips;
};
// 定义表头列类型
interface TableColumn {
  key: string;
  label: string;
  width?: string;
  flex?: boolean;
  align?: 'left' | 'center' | 'right';
  justify?: 'left' | 'center' | 'right';
}

// Props
interface Props {
  title?: string;
  tableData?: any[];
  frequencyOptions?: Array<any>;
  defaultActiveType?: 'inspection' | 'examination';
  columns?: TableColumn[];
  prescriptionData?: any;
  visitStatus?: string; // 新增的处方状态属性
  onZS?: any;
  weight?: number;
  uuid?: string;
  displayNowUUid?: string;
}
// 数字键盘相关
// const displayNowUUid = ref('');
const keyboardVisible = ref(false);
const currentEditRow = ref<any | null>(null);
const currentEditField = ref<any>(null);
const props = withDefaults(defineProps<Props>(), {
  title: '查验项目',
  tableData: () => [],
  frequencyOptions: () => [],
  defaultActiveType: 'inspection',
  prescriptionData: () => {},
  onZS: () => {},
  weight: 0,
  uuid: '',
  displayNowUUid: '',
  visitStatus: '1', // 1.未审核 2.已审核
  columns: () => [
    {
      key: 'index',
      label: '序号',
      width: '70px',
      align: 'center',
      justify: 'center',
    },
    { key: 'drugName', label: '药品', width: '250px' },
    { key: 'usageCodeText', label: '用法', width: '109px' },
    { key: 'frequencyCode', label: '频率', width: '140px' },
    { key: 'dosage', label: '用量/次', width: '130px' },
    { key: 'cycle', label: '周期', width: '100px' },
    { key: 'totalOutQty', label: '总量', width: '100px' },
    { key: 'remark', label: '备注', flex: true },
  ],
});

// Emits
const emit = defineEmits<{
  'update:tableData': [value: any[]];
  'active-type-change': [type: 'inspection' | 'examination'];
  'row-update': [row: any, index: number];
  'search-result-select': [result: any];
  removeRow: [result: any];
  searchKeyboard: any;
}>();

// 响应式数据
const activeType = ref<'inspection' | 'examination'>(props.defaultActiveType);
const searchText = ref('');
const searchKeyboardVisible = ref(false);
const keyboardMode = ref<'english' | 'chinese'>('english');
const searchResults = ref<any[]>([]);

// 添加 hoveredRow 响应式变量
const hoveredRow = ref<any>(null);

// 添加防抖定时器引用
const debounceTimer = ref<any>(null);
// 获取列的样式
const getColumnStyle = (column: TableColumn) => {
  return {
    width: column.flex ? undefined : column.width,
    flex: column.flex ? 1 : undefined,
    textAlign: column.align || 'left',
    justifyContent: column.justify || 'left',
  };
};
const displayTableData = ref<any[]>([]);
const displayNow = ref<any>({});
// 计算属性：过滤后的表格数据
watch(
  () => props.prescriptionData,
  (newVal) => {
    //console.log(newVal);
    displayNow.value = newVal;
    displayNow.value.detailList = newVal.detailList.map((item: any) => ({
      ...item,
      projectCategoryName: useBaseDataStore.getEnumData(
        item.projectCategory,
        'projectCategoryEnum'
      ),
      cycleUnitText: useBaseDataStore.getEnumData(
        item.cycleUnit,
        'cycleUnitEnum'
      ),
      totalOutQtyUnitText: useBaseDataStore.getDictsData(
        item.totalOutQtyUnit,
        'UNIT'
      ),
      tips: generateTips(item),
      dosageUnitText: useBaseDataStore.getDictsData(item.dosageUnit, 'UNIT'),
      uuid: uuidv4(), // 为每一行添加唯一标识符
      specification:
        item.drugCategory == 3
          ? `${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`
          : `${item.drugDosage}${item.drugDosageUnitText}*${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`,
    }));

    // generateTips
    //console.log(displayNow.value.detailList);
  },
  { immediate: true }
);
watch(
  () => props.weight,
  (newVal) => {
    displayNow.value.detailList = displayNow.value.detailList.map(
      (item: any) => ({
        ...item,
        projectCategoryName: useBaseDataStore.getEnumData(
          item.projectCategory,
          'projectCategoryEnum'
        ),
        cycleUnitText: useBaseDataStore.getEnumData(
          item.cycleUnit,
          'cycleUnitEnum'
        ),
        totalOutQtyUnitText: useBaseDataStore.getDictsData(
          item.totalOutQtyUnit,
          'UNIT'
        ),
        tips: generateTips(item),
        dosageUnitText: useBaseDataStore.getDictsData(item.dosageUnit, 'UNIT'),
        uuid: uuidv4(), // 为每一行添加唯一标识符
        specification:
          item.drugCategory == 3
            ? `${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`
            : `${item.drugDosage}${item.drugDosageUnitText}*${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`,
      })
    );
  },
  { immediate: true }
);
// 方法
const setActiveType = (type: 'inspection' | 'examination') => {
  activeType.value = type;
  emit('active-type-change', type);
};

// 添加 showMedicineInfo 方法
const showMedicineInfo = async (row: any) => {
  const data = row;
  hoveredRow.value = row.uuid;
  drugProfileDetail.value = data;
  // drugProfileDetail.value.specification =
  //   drugProfileDetail.value.drugDosage +
  //   drugProfileDetail.value.drugDosageUnitText +
  //   '*' +
  //   drugProfileDetail.value.minPackQty +
  //   drugProfileDetail.value.minPackUnitText +
  //   '/' +
  //   drugProfileDetail.value.packUnitText;

  (drugProfileDetail.value.specification =
    drugProfileDetail.value.drugCategory == 3
      ? `${drugProfileDetail.value.minPackQty}${drugProfileDetail.value.minPackUnitText}/${drugProfileDetail.value.packUnitText}`
      : `${drugProfileDetail.value.drugDosage}${drugProfileDetail.value.drugDosageUnitText}*${drugProfileDetail.value.minPackQty}${drugProfileDetail.value.minPackUnitText}/${drugProfileDetail.value.packUnitText}`),
    (drugProfileDetail.value.mfrName = useBaseDataStore.getMfrName(
      drugProfileDetail.value.mfrId
    ));
  drugProfileDetail.value.drugCategoryName = useBaseDataStore.getEnumData(
    drugProfileDetail.value.drugCategory,
    'drugCategoryEnum'
  );
};
const showMedicineInfoRow = (row: any) => {
  AlertTipsRow.value = row.uuid;
};
const hideMedicineInfoRow = () => {
  setTimeout(() => {
    AlertTipsRow.value = '';
  });
};

// 添加 hideMedicineInfo 方法
const hideMedicineInfo = () => {
  //console.log(hoveredRow.value);
  hoveredRow.value = null;
};

const updateRow = (row: any, index: number) => {
  //console.log(row);

  emit('row-update', row, index);
};
// 用法弹窗相关
const showMedicationTabs = ref<boolean>(false);
// 获取单位名称的方法
const getUnitName = (unitCode: string) => {
  const UNITDATA = useBaseDataStore.getDictsSelect('UNIT') || [];
  // 过滤出unitType等于2的数据
  const filteredUnits = UNITDATA.filter(
    (unit: any) => unit.unitType === '2' || unit.unitType === 2
  );
  // 根据unitCode查找对应的单位名称
  const foundUnit = filteredUnits.find(
    (unit: any) => unit.unitCode === unitCode
  );
  //console.log(foundUnit);

  return foundUnit ? foundUnit.unitText : unitCode; // 如果找不到就返回原始unitCode
};
const onSelect = (row: any, usage: any, usageName: any) => {
  row.usageCode = usage.value[0];
  row.usageCodeText = usageName;
  // // 判断是否已存在，存在则更新，不存在则添加
  // const idx = detailList.value.findIndex(
  //   (item) => item.drugId === currentUsageRow.value.drugId
  // );
  // if (idx > -1) {
  //   detailList.value[idx] = {
  //     ...detailList.value[idx],
  //     ...currentUsageRow.value,
  //   };
  // } else {
  //   detailList.value.push({ ...currentUsageRow.value });
  // }
  // prescriptionTypeList.value.forEach((item: any) => {
  //   if (item.rxType == '1') {
  //     item.detailList = detailList.value;
  //   }
  // });
  showMedicationTabs.value = false;
};
const onUsageCode = (row: any) => {
  isShowMedicationTabs.value = row.uuid;
  if (currentUsageRow.value === row && showMedicationTabs.value) {
    // 再次点击同一行则关闭
    showMedicationTabs.value = false;
    currentUsageRow.value = null;
  } else {
    showMedicationTabs.value = true;
    currentUsageRow.value = row;
  }
  searchKeyboardVisible.value = false;
  searchResults.value = [];
};
const updataTemplate = (templates: any) => {
  //console.log(templates);
  isTemplate.value = false;
};
const querySearchAsync = (queryString: string, cb: any) => {
  const data1 = useBaseDataStore.getDictsSelect('REMARK') || [];
  // 仅保留 rxType 为 5 的项（兼容数字/字符串）
  const filtered = (Array.isArray(data1) ? data1 : []).filter(
    (item: any) => item?.rxType === 5 || item?.rxType === '1'
  );
  const results = filtered.map((item: any) => ({
    value: item.remarkText,
    ...item,
  }));
  cb(results);
};
const onFrequency = (row: any, index: number) => {
  const selectedFrequency = props.frequencyOptions?.find(
    (freq) => freq.frequencyCode === row.frequencyCode
  );
  // frequencyCodeText
  if (selectedFrequency) {
    row.cycleUnit = selectedFrequency.cycleUnit;
    (row.cycleUnitText = useBaseDataStore.getEnumData(
      selectedFrequency.cycleUnit,
      'cycleUnitEnum'
    )),
      updateRow(row, index);
  }
};
// 保存模板
const onAddTemplate = async (data: any) => {
  // //console.log('保存模板数据:', data);
  //   const examList= fields.value.map((item: { fieldId: any; fieldValue: any; fieldImages: any;})=>{
  //   return {
  //     fieldId: item.fieldId,
  //     fieldValue: item.fieldValue,
  //     fieldImages: item.fieldImages,
  //   }
  // })
  // const data1 = {
  //   ...data,
  //   recomScene: '',
  //   fieldList: examList,
  // }
  // const result = await addTemplateMedical(data1);
  ElMessage.success('模板保存成功');
};
// 搜索方法
const handleSearch = async (value: string) => {
  //console.log('搜索内容:', value);

  // 模拟搜索结果数据

  // 根据图片显示的结果
  const recomsRaw = props.onZS();
  const recoms =
    typeof recomsRaw === 'string' ? recomsRaw.replace(/，/g, ',') : recomsRaw;
  const result = await getDrugRxList({
    drugName: value,
    storageId: displayNow.value.storageId,
    drugCategory: '1',
    recoms,
  });
  if (result?.code != '200') {
    //ElMessage.error(result?.msg);
    return;
  }
  searchResults.value =
    result?.data.map((item: any) => ({
      ...item,
      drugCategoryName: useBaseDataStore.getEnumData(
        item.drugCategory,
        'drugCategoryEnum'
      ),
      specification:
        item.drugCategory == 3
          ? `${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`
          : `${item.drugDosage}${item.drugDosageUnitText}*${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`,
      usageCode: item.usageList[0]?.usageCode || '',
      usageCodeText: useBaseDataStore.getDictsUSAGEData(
        item.usageList[0]?.usageCode,
        'USAGE'
      ),
      frequencyCode: '',
      frequencyCodeText: '',
      dosage: item.drugDosage,
      dosageUnit: item.drugDosageUnit,
      dosageUnitText: item.drugDosageUnitText,
      cycle: '',
      cycleUnit: '',
      cycleUnitText: '',
      totalOutQty: '',
      totalOutQtyUnit: item.packUnit,
      totalOutQtyUnitText: item.packUnitText,
      mfrName: useBaseDataStore.getMfrName(item.mfrId),
      minPackQty: item.minPackQty,
      isSplit: item.isSplit,
      price: item.price,
      splitPrice: item.splitPrice,
    })) || [];
};
// 搜索键盘相关方法
const showSearchKeyboard = () => {
  searchKeyboardVisible.value = true;
  //console.log(props?.uuid,'-----------------');
  // displayNowUUid.value = ''
  // displayNowUUid.value = props?.uuid;
  emit('searchKeyboard');
  currentEditRow.value = null;
  currentEditField.value = null;
  showMedicationTabs.value = false;
  document.addEventListener('keydown', handleKeyboardShortcut);
  handleSearch(searchText.value);
};

const hideSearchKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (
      target.closest('.search-keyboard') ||
      target.closest('.search-results1') ||
      target.closest('.search-input1')
    ) {
      return;
    }
  }

  //  displayNowUUid.value = ''
  searchKeyboardVisible.value = false;
  searchResults.value = [];
  document.removeEventListener('keydown', handleKeyboardShortcut);
};

const handleKeyboardShortcut = (event: KeyboardEvent) => {
  if (event.ctrlKey && event.shiftKey && event.key === 'T') {
    event.preventDefault();
    switchKeyboard();
  } else if (event.key === 'Escape') {
    event.preventDefault();
    hideSearchKeyboard();
  }
};
// 添加 showChart 和 hideChart 方法
const showChart = (column: string, row: any) => {
  chartVisible.value = row;
  chartVisibleColumn.value = column;
  const usageList = row?.usageList.find(
    (item: any) => item.usageCode === row?.usageCode
  );
  //console.log(usageList, '2');

  if (!usageList) {
    isUserCode.value = false;
  }
};
const changeVisible = (row: any) => {
  console.log(row);
  displayNow.value.detailList.forEach(
    (element: { uuid: any; dosage: boolean }) => {
      if (element.uuid === row.uuid) {
        element.dosage = row.value;
      }
    }
  );
  chartVisibleColumn.value = null;
  isUserCode.value = true;
  chartVisible.value = {};
  // chartVisible.value = row;
  // chartVisibleColumn.value = column;
  // const usageList = row?.usageList.find(
  //   (item: any) => item.usageCode === row?.usageCode
  // );
  // //console.log(usageList, '2');

  // if (!usageList) {
  //   isUserCode.value = false;
  // }
};

const hideChart = (event: any) => {
  console.log(event);
  if (event && event.target.nodeName == 'CANVAS') {
    const target = event.target as Element;
    return;
  }
  chartVisibleColumn.value = null;
  isUserCode.value = true;
  chartVisible.value = {};
};

const inputSearchChar = (char: string) => {
  searchText.value += char;
  handleSearch(searchText.value);
};
const onfrequency = () => {
  showMedicationTabs.value = false;

  searchKeyboardVisible.value = false;
  // displayNowUUid.value = ''
  searchResults.value = [];
};

const deleteSearchChar = () => {
  if (searchText.value.length > 0) {
    searchText.value = searchText.value.slice(0, -1);
    handleSearch(searchText.value);
  }
};

const clearSearch = () => {
  searchText.value = '';
  searchResults.value = [];
};

const switchKeyboard = () => {
  if (keyboardMode.value === 'english') {
    keyboardMode.value = 'chinese';
  } else if (keyboardMode.value === 'chinese') {
    keyboardMode.value = 'english';
  } else {
    keyboardMode.value = 'english';
  }
};

const selectSearchResult = (result: any) => {
  result.uuid = uuidv4(); // 为每一行添加唯一标识符
  result.usageCodeText = '口服'; // 标记为非新行
  result.usageCode = 'KF'; // 默认用法代码
  result.frequencyCode = 'tid'; // 默认频率代码
  result.cycleUnit = 'day';
  result.cycleUnitText = '天';
  result.dosage = null;
  result.cycle = null;
  result.totalOutQty = null;
  // 确保价格计算所需字段存在
  result.minPackQty = result.minPackQty ?? 0;
  result.isSplit = result.isSplit;
  result.price = result.price ?? 0; // 分
  result.splitPrice = result.splitPrice ?? 0; // 分
  result.remark = result.instrs;
  displayNow.value.detailList.push(result);
  searchKeyboardVisible.value = false;
  // displayNowUUid.value = ''
  searchResults.value = [];
  searchText.value = '';
};

// 数字键盘相关方法
const showKeyboard = (row: any, index: number, field: string) => {
  currentEditRow.value = row;
  currentEditField.value = field;
  if (field === 'dosage') {
    showChart('1', row);
  }
  keyboardVisible.value = true;
  showMedicationTabs.value = false;
  searchKeyboardVisible.value = false;
  // displayNowUUid.value = ''
  searchResults.value = [];
  // 确保字段有初始值
  if (row[field] === undefined || row[field] === null) {
    row[field] = null;
    //console.log('showKeyboard: initialized field value to 1', field);
  }
};
const inputNumber = (num: string, type?: string) => {
  console.log('键盘输入值:', num, '类型:', type);
  if (type) {
    // 直接设置数值（来自NumberDecimal组件）
    currentEditRow.value[currentEditField.value] = Number(num);
    if (currentEditField.value !== 'totalOutQty') {
      recalcRowTotalOutQty(currentEditRow.value);
    }
    return;
  }

  // 有效性检查
  if (!currentEditRow.value || !currentEditField.value) {
    return;
  }

  // 获取当前值和字段配置
  const field = currentEditField.value;
  const currentValue = currentEditRow.value[field];
  const isDecimalField = ['dosage', 'splitPrice'].includes(field); // 假设这些字段允许小数

  // 处理小数点输入
  if (num === '.') {
    // if (!isDecimalField) {
    //   //console.log('小数点输入被拒绝，该字段不支持小数');
    //   return;
    // }

    // 如果当前值已经是小数或包含小数点，不再添加
    const currentStr = currentValue?.toString() || '';
    if (currentStr.includes('.')) {
      return;
    }

    // 添加小数点
    currentEditRow.value[field] = currentStr + '.';
    return;
  }

  // 处理数字输入
  let newValue: number | string;

  // 初始化或处理现有值
  if (currentValue === undefined || currentValue === null) {
    newValue =
      isDecimalField && currentEditRow.value[field]?.toString().includes('.')
        ? '0.' + num
        : num;
  } else {
    const currentStr = currentValue.toString();

    if (isDecimalField && currentStr.includes('.')) {
      // 小数部分拼接
      const [integer, decimal] = currentStr.split('.');
      newValue = `${integer}.${decimal}${num}`;
    } else {
      // 整数部分拼接
      newValue = currentStr === '0' ? num : currentStr + num;
    }
  }

  // 转换为数字并验证范围
  const numericValue = Number(newValue);
  const maxValue = 999; // 根据字段获取最大值

  if (numericValue <= maxValue) {
    currentEditRow.value[field] = isDecimalField
      ? numericValue
      : Math.floor(numericValue);

    // 如果不是总量字段，则重新计算总量
    if (field !== 'totalOutQty') {
      recalcRowTotalOutQty(currentEditRow.value);
    }
  } else {
  }
};

const removeRow_1 = (group: any) => {
  if (group) {
    emit('removeRow', displayNow.value.detailList);
  }
};
// 点击其他地方关闭 MedicationTabs
const handleGlobalClick = (event: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.medication-tabs')) {
      return;
    }
  }
  showMedicationTabs.value = false;
  currentUsageRow.value = null;
};
// 选择药品
const onStorage = async (list: any) => {
  // displayNow.value.storageId = row.storageId;
  // displayNow.value.storageName = row.storageName;
  // displayNow.value.detailList = [];
  const drugIdList = list.map((item: any) => item.drugId);
  const result = await getDrugRxList({
    drugIdList: drugIdList.join(','),
    storageId: displayNow.value.storageId,
  });
  if (result?.code != '200') {
    //ElMessage.error(result?.msg);
    return;
  }

  // 根据需求，将result.data中的stockQty、minStockQty、stockWarningQty赋值给displayNow.value.detailList中相同drugId的项目
  if (result.data && Array.isArray(result.data)) {
    displayNow.value.detailList.forEach((item: any) => {
      const matchingItem = result.data.find(
        (dataItem: any) => dataItem.drugId === item.drugId
      );
      if (matchingItem) {
        item.stockQty = matchingItem.stockQty;
        item.minStockQty = matchingItem.minStockQty;
        item.stockWarningQty = matchingItem.stockWarningQty;
        item.tips = generateTips(item);
      }
    });
  }
};
const hideKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;

    if (target.closest('.number-keyboard')) {
      return;
    }
  }

  keyboardVisible.value = false;
  // currentEditRow.value = null;
  // currentEditField.value = null;
};

const deleteNumber = () => {
  if (!currentEditRow.value || !currentEditField.value) {
    //console.log('deleteNumber: currentEditRow or currentEditField is null');
    return;
  }

  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    //console.log('deleteNumber: current value is undefined/null');
    return;
  }

  // const currentValueStr = currentValue.toString();
  // const newValue = parseInt(currentValueStr.slice(0, -1)) || 1;
  // currentEditRow.value[currentEditField.value] = newValue;
  const currentValueStr = currentValue.toString();
  const newValue = currentValueStr.slice(0, -1);
  currentEditRow.value[currentEditField.value] =
    newValue === '' ? null : parseInt(newValue);
  if (currentEditField.value != 'totalOutQty') {
    recalcRowTotalOutQty(currentEditRow.value);
  }
};

const confirmAdd = (row: any, index: number) => {
  if (!row.projectName.trim()) {
    ElMessage.warning('请选择项目');
    return;
  }

  // const newItem: any = {
  //   id: Date.now(),
  //   name: row.name,
  //   category: activeType.value === 'inspection' ? '检验' : '检查',
  //   frequency: row.frequency,
  //   period: row.period,
  //   totalCount: row.totalCount,
  //   remark: row.remark || '新添加项目',
  // };

  // const updatedData = [...props.tableData, newItem];
  // emit('update:tableData', updatedData);
  // ElMessage.success('项目添加成功');
};

// 删除行方法
const deleteRow = (row: any, index: number) => {
  //console.log(row);

  displayNow.value.detailList = displayNow.value.detailList.filter(
    (item: { uuid: any }) => item.uuid !== row.uuid
  );
  emit('update:tableData', displayNow.value.detailList);
  if (displayNow.value.detailList.length === 0) {
    emit('update:tableData', []);
    displayNow.value.totalAmount = 0;
  }
  ElMessage.success('项目删除成功');
};
// 选择模板
const onSelectTemplate = () => {
  isTemplate.value = true;
};
// 生命周期钩子
onMounted(() => {
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
    hideSearchKeyboard(event);
    handleGlobalClick(event);
    hideChart(event);
  };
  document.addEventListener('mousedown', globalClickHandler);
});

onUnmounted(() => {
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
    hideSearchKeyboard(event);
    handleGlobalClick(event);
    hideChart(event);
  };
  document.removeEventListener('mousedown', globalClickHandler);
});
// ============== 价格与总量计算（使用 rxUtil） START ==============
// 从频率代码获取每天次数
function getTimesPerDayFromCode(code: string): number {
  if (!code) return 0;
  const item = props.frequencyOptions?.find(
    (f: any) => f.frequencyCode === code
  );
  return Number(item?.frequencyTimes) || 0;
}

function recalcRowTotalOutQty(row: any) {
  const dosage = Number(row.dosage);
  const cycle = Number(row.cycle);
  const times = getTimesPerDayFromCode(row.frequencyCode);
  if (!times || !dosage || dosage <= 0 || !cycle || cycle <= 0) return;
  row.totalOutQty = calculateTotalDose(
    dosage,
    times,
    cycle,
    row.isMinSplit,
    row?.isSplit,
    row.minPackQty
  );
}

function recalcTotalAmount() {
  const list = Array.isArray(displayNow.value?.detailList)
    ? displayNow.value.detailList
    : [];
  let sum = 0;
  for (const row of list) {
    const qty = Number(row.totalOutQty);
    const minPackQty = Number(row.minPackQty);
    const price = Number(row.price); // 分
    const splitPrice = Number(row.splitPrice); // 分
    if (!qty || qty <= 0 || !minPackQty) continue;
    const { totalPrice } = calculatePrice(
      qty,
      minPackQty,
      row?.isSplit,
      price,
      splitPrice
    );
    sum += Number.isFinite(totalPrice) ? totalPrice : 0;
  }
  //console.log(sum);

  displayNow.value.totalAmount = sum;
}
function getDeepChanges(newObj: any[], oldObj: any[], path = '') {
  if (!oldObj) return [{ path, newValue: newObj }];

  if (Array.isArray(newObj)) {
    const changes: any[] = [];
    newObj.forEach((item, index) => {
      changes.push(...getDeepChanges(item, oldObj[index], `${path}[${index}]`));
    });
    return changes;
  }

  return newObj !== oldObj
    ? [{ path, oldValue: oldObj, newValue: newObj }]
    : [];
}
function extractDifferences(changeItems: any[]) {
  // 深度比较两个值是否相等
  function isDeepEqual(
    a: { [x: string]: any } | null,
    b: { [x: string]: any } | null
  ) {
    if (a === b) return true;
    if (
      typeof a !== 'object' ||
      a === null ||
      typeof b !== 'object' ||
      b === null
    )
      return false;

    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;

    for (const key of keysA) {
      if (!keysB.includes(key)) return false;
      if (!isDeepEqual(a[key], b[key])) return false;
    }
    return true;
  }

  return changeItems
    .map((item) => {
      const { path, oldValue, newValue } = item;
      const uuid = newValue?.uuid || oldValue?.uuid; // 获取UUID

      const changedFields: any = {};

      // 收集所有key，包括oldValue和newValue中的
      const allKeys = new Set([
        ...Object.keys(oldValue || {}),
        ...Object.keys(newValue || {}),
      ]);

      // 比较每个字段
      for (const key of allKeys) {
        const oldVal = oldValue?.[key];
        const newVal = newValue?.[key];
        // 只有当值确实不同时才记录
        if (!isDeepEqual(oldVal, newVal)) {
          changedFields[key] = {
            old: oldVal,
            new: newVal,
            uuid: uuid,
          };
        }
      }

      // 只返回有实际变化的项
      return Object.keys(changedFields).length > 0
        ? { path, changes: changedFields, uuid }
        : null;
    })
    .filter(Boolean); // 过滤掉没有实际变化的项
}
// 监听处方行的关键字段变化：频率、用量、周期、总量，以及价格相关字段
watch(
  () =>
    (Array.isArray(displayNow.value?.detailList)
      ? displayNow.value.detailList
      : []
    ).map((r: any) => ({
      id: r.uuid || r.drugId || r.projectId,
      f: r.frequencyCode,
      d: r.dosage,
      c: r.cycle,
      uuid: r.uuid,
      code: r.usageCode,
      tq: r.totalOutQty,
    })),
  (nval, cval) => {
    // 先补全 totalOutQty
    const diffs = extractDifferences(getDeepChanges(nval, cval));
    //console.log('实际变化的字段:', diffs);

    // 获取所有变化的UUID
    const changedUUIDs = diffs.map((diff: any) => diff.uuid).filter(Boolean);
    if (displayNow.value.detailList.length == 0) {
      return;
    }
    for (const row of displayNow.value.detailList || []) {
      row.tips = generateTips(row);
      if (
        currentEditField.value != 'totalOutQty' &&
        changedUUIDs.includes(row.uuid) &&
        props.visitStatus !== '2'
      ) {
        recalcRowTotalOutQty(row);
      }
    }

    // 再汇总价格
    recalcTotalAmount();
  },
  { deep: true, immediate: true }
);
// ============== 价格与总量计算（使用 rxUtil） END ==============
defineExpose({
  displayNow,
});
</script>

<style lang="scss" scoped>
::v-deep(.custom-transition-dialog-1) {
  padding: 0 !important;

  .el-dialog__header {
    padding: 0 !important;
  }
}

// 自定义表格样式
.custom-table {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  // overflow: visible;
  border-radius: 12px 12px 12px 12px;
  position: relative;
  background: #ffffff;
  margin-bottom: 10px;

  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 16px 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .action-buttons {
      display: flex;
      align-items: center;

      .el-button.active {
        background-color: #409eff;
        color: white;
        border-color: #409eff;
      }
    }
  }

  .table-header {
    display: flex;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;

    .header-cell {
      padding: 12px 8px;
      text-align: center;
      font-weight: 600;
      color: #909399;
      font-size: 14px;
      border-right: none;
      align-items: center;
      cursor: pointer;
    }
  }

  .table-row-container {
    position: relative;
    display: flex;
    align-items: center;

    &:hover {
      .delete-button {
        opacity: 1;
        visibility: visible;
      }
    }

    .table-row {
      flex: 1;
      display: flex;
      border-bottom: 1px solid #e4e7ed;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: #f5f7fa;
      }

      &.add-row {
        background-color: #fafafa;
      }

      .table-cell {
        display: flex;
        padding: 0 8px;
        align-items: center;
        align-items: center;
        border-right: none;
        min-height: 50px;
        position: relative;
        // overflow: hidden;
        text-overflow: ellipsis;

        &:last-child {
          justify-content: flex-start;
          // padding-left: 12px;
        }

        &:has(.number-keyboard) {
          overflow: visible;
          z-index: 1;
        }
      }
    }

    .delete-button {
      position: absolute;
      right: -17px;
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #989898;
      border-radius: 50%;
      cursor: pointer;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
      z-index: 10;

      &:hover {
        transform: translateY(-50%) scale(1.1);
      }

      img {
        width: 16px;
        height: 16px;
        filter: brightness(0) invert(1); // 将图标变为白色
      }
    }
  }

  .table-row {
    display: flex;
  }
}

.table-header-1 {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  gap: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;

  .header-cell {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #333333;

    .delete-icon {
      color: #c0c4cc;
      cursor: pointer;

      &:hover {
        color: #f56c6c;
      }
    }
  }
}

// 无边框输入框样式
:deep(.borderless-select) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
  }

  &:hover .el-input__wrapper {
    border-color: #c0c4cc;
  }

  &.is-focus .el-input__wrapper {
    border-color: #409eff;
  }
}

:deep(.borderless-input) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
  }

  &:hover .el-input__wrapper {
    border-color: #c0c4cc;
  }

  &.is-focus .el-input__wrapper {
    border-color: #409eff;
  }
}

:deep(.no-border-input) {
  .el-input__wrapper {
    box-shadow: none;
    padding: 0;
  }
}

// 数字键盘样式
.number-keyboard {
  position: absolute;
  top: 70%;
  left: 0;
  z-index: 9999 !important;
  // background: white;
  // border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 8px;
  margin-top: 4px;
  transform: translateZ(0);

  .keyboard-row {
    display: flex;
    gap: 4px;
    margin-bottom: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    width: 50px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #f8f9fa;
    color: #333;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      width: 104px;
      background: #f56c6c;
      color: white;
      font-size: 14px;

      &:hover {
        background: #f78989;
      }
    }
  }
}

// 搜索行样式
.search-row {
  .table-cell {
    border-right: none;

    &:first-child {
      padding-left: 17px;
      display: flex;
      width: 100%;
    }
  }

  .search-input1 {
    :deep(.el-input__wrapper) {
      background-color: transparent;
      box-shadow: none;
      border-radius: 4px;
      height: 50px;
    }

    :deep(.el-input__inner) {
      font-weight: 500;

      &::placeholder {
        font-weight: normal;
      }
    }

    :deep(.el-input__prefix) {
      color: #f87171;
    }
  }
}

// 搜索键盘样式
.search-keyboard {
  position: absolute;
  top: -250px;
  left: 0;
  z-index: 9999;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
  width: 600px;
  max-width: 90vw;

  .keyboard-row {
    display: flex;
    gap: 6px;
    margin-bottom: 8px;
    justify-content: center;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    min-width: 45px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #ffffff;
    color: #333;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8px;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.clear-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.switch-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.space-btn {
      min-width: 60px;
      color: rgb(0, 0, 0);
    }
  }
}

// 搜索结果样式
.search-results1 {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9998;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  margin-top: 4px;
  max-height: 300px;
  overflow-y: auto;
  width: 100%;

  // 重写搜索结果中的表头样式，确保与内容对齐
  .table-header {
    .header-cell {
      text-align: left !important;
      justify-content: flex-start !important;
    }
  }

  .search-result-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f5f7fa;
    cursor: pointer;
    text-align: left;
    transition: background-color 0.2s;
    height: 48px; // 设置固定高度

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: #f0f9ff;
    }

    // 清除子元素样式，使用内联样式控制
    .result-name,
    .result-category,
    .result-spec,
    .result-price {
      display: flex;
      align-items: center;
      height: 100%;
      font-size: 14px;
      color: #333;
    }

    .result-category,
    .result-spec {
      font-size: 12px;
      color: #666;
    }

    .result-price {
    }
  }
}

/* 胶囊连体样式：数字 + 单位 */
.pill-input-unit {
  display: inline-flex;
  align-items: stretch;
  /* 子项拉伸到满高，分割线能顶到上下 */
  border: 1px solid #e5e7eb;
  /* 与截图接近的淡灰边 */
  border-radius: 8px;
  /* 外层圆角 */
  height: 32px;
  /* 统一高度 */
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.02) inset;
  /* 轻微内阴影增强层次 */
  background: #ffffff;
  position: relative;
  overflow: visible;
}

/* 左侧数字输入框圆角和分割线处理 */
:deep(.pill-number) {
  .el-input__wrapper {
    box-shadow: none;
    border-radius: 5px;
    /* 左侧外角圆角 */
    height: 32px;
    /* 与外层一致，保证分割线满高 */
    padding: 0 8px;
  }

  /* 输入宽度紧凑 */
  width: 56px !important;
}

/* 右侧单位胶囊 */
.unit-chip {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
  height: 100%;
  /* 与外层一致，分割线满高 */
  color: #606266;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  /* 与左侧分隔 */
  border-left: none;
  /* 避免双边框 */
  border-radius: 0 5px 5px 0;
  /* 右侧外角圆角 */
  user-select: none;
}

/* 悬浮态微妙变化 */
.pill-input-unit:hover {
  border-color: #dcdfe6;
}

.move-Medicine {
  width: 386px;
  box-shadow: 0px 12px 32px 0px rgba(0, 0, 0, 0.2);
  border-radius: 12px 12px 12px 12px;
  position: absolute;
  bottom: 20px;
  z-index: 9999;
  background-color: white;
}

.move-Medicine-icon {
  width: 386px;
  height: 62px;
  background: linear-gradient(90deg, #f5fefd 0%, #fbfbfa 100%);
  border-radius: 11px 11px 0px 0px;
  display: flex;
  justify-content: space-between;
  padding: 10px;
}

.chart-overlay {
  position: absolute;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  width: 400px;
  height: 300px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
  z-index: 1000;
}
.multi-line {
  display: -webkit-box; /* 使用flexbox布局 */
  -webkit-line-clamp: 2; /* 限制显示行数 */
  -webkit-box-orient: vertical; /* 垂直排列 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>
